package com.nutiteq.mapper.forms;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import com.nutiteq.components.KmlPlace;
import com.nutiteq.components.WgsPoint;
import com.nutiteq.mapper.MapScreen;
import com.nutiteq.mapper.Mapper;
import com.nutiteq.services.CloudMadeGeocodingService;
import com.nutiteq.services.GeocodingResultWaiter;
import com.nutiteq.services.GeocodingService;

public class SearchForm extends Form implements CommandListener, GeocodingResultWaiter {
  public static final Command SEARCH_PLACENAMES = new Command("Search places", Command.ITEM, 0);

  private final TextField what;
  private final ChoiceGroup searchType;
  private final Command back;
  private final Command search;
  private final WgsPoint center;
  private final MapScreen mapScreen;
  private TextField objectType;
  private final String[] objectTypes=new String[]{"UNDEFINED",
      "poi",
      "road",
      "area",
      "aerodrome",
      "apron",
      "baby_hatch",
      "bicycle_parking",
      "bicycle_rental",
      "bus_station",
      "bus_guideway",
      "bus_stop",
      "cemetery",
      "city_wall",
      "college",
      "courthouse",
      "crane",
      "crossing",
      "cycleway",
      "dam",
      "dock",
      "drag_lift",
      "drain",
      "emergency_access_point",
      "farm",
      "farmyard",
      "fell",
      "ferry",
      "ferry_terminal",
      "fire_station",
      "footway",
      "forest",
      "gate",
      "generator",
      "grave_yard",
      "grit_bin",
      "halt",
      "heath",
      "helipad",
      "island",
      "library",
      "lighthouse",
      "line",
      "living_street",
      "locality",
      "lock_gate",
      "marsh",
      "mini_roundabout",
      "monorail",
      "motorway",
      "motorway_junction",
      "motorway_link",
      "naval_base",
      "path",
      "pedestrian",
      "pillbox",
      "pipeline",
      "place_of_worship",
      "platform",
      "police",
      "post_box",
      "post_office",
      "primary",
      "prison",
      "public building",
      "rail",
      "railway",
      "recycling",
      "reservoir",
      "retaining_wall",
      "river",
      "riverbank",
      "roundabout",
      "runway",
      "school",
      "secondary",
      "service",
      "services",
      "station",
      "steps",
      "stile",
      "stream",
      "sub_station",
      "suburb",
      "subway_entrance",
      "surveillance",
      "survey_point",
      "taxiway",
      "telephone",
      "terminal",
      "tertiary",
      "town",
      "townhall",
      "track",
      "traffic signals",
      "tram_stop",
      "tree",
      "trunk",
      "trunk_link",
      "turning_circle",
      "turning_point",
      "turntable",
      "university",
      "village",
      "village_green",
      "waste_disposal",
      "wastewater plant",
      "water",
      "weir",
      "windmill",
      "wood",
      "foot",
      "parking_aisle",
      "fuel",
      "level_crossing",
      "parking",
      "stop",
      "toll_booth",
      "cafe",
      "drinking water",
      "fast_food",
      "pub",
      "restaurant",
      "chalet",
      "hostel",
      "hotel",
      "motel",
      "residential",
      "crematorium",
      "hospital",
      "pharmacy",
      "veterinary",
      "bakery",
      "bicycle",
      "butcher",
      "convenience",
      "doityourself",
      "dry_cleaning",
      "florist",
      "kiosk",
      "outdoor",
      "archaeological_site",
      "arts_centre",
      "artwork",
      "battlefield",
      "beacon",
      "camp_site",
      "car_rental",
      "car_sharing",
      "castle",
      "cattle_grid",
      "cave_entrance",
      "cliff",
      "coastline",
      "glacier",
      "information",
      "memorial",
      "museum",
      "peak",
      "spring",
      "tower",
      "viewpoint",
      "volcano",
      "watermill",
      "wreck",
      "beach",
      "boatyard",
      "bollard",
      "bridleway",
      "cable_car",
      "canal",
      "chair_lift",
      "cinema",
      "common",
      "fountain",
      "park",
      "pier",
      "playground",
      "recreation_ground",
      "slipway",
      "theatre",
      "vending_machine",
      "zoo",
      "shooting",
      "stadium",
      "atm",
      "atm",
      "bank",
      "bureau_de_change",
      "nightclub",
      "studio",
      "taxi"      
      };

  private ChoiceGroup around;
  
  public SearchForm(final MapScreen mapScreen, final WgsPoint center) {
    super("Search");
    this.mapScreen = mapScreen;
    this.center = center;

    what = new TextField("Query", "", 50, TextField.ANY);
    searchType = new ChoiceGroup("ObjectType", Choice.POPUP );
    for (int i=0;i<objectTypes.length;i++){
      searchType.append(objectTypes[i], null);  
    }

    around = new ChoiceGroup("Search around", ChoiceGroup.EXCLUSIVE);
    around.append("anywhere", null);
    around.append("map center", null);

    
    back = new Command("Back", Command.BACK, 0);
    search = new Command("Search", Command.OK, 0);

    append(what);
    append(around);
    append(searchType);
    addCommand(back);
    addCommand(search);

    setCommandListener(this);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == back) {
      Display.getDisplay(Mapper.instance).setCurrent(MapScreen.instance);
    } else if (cmd == search) {
      if ("".equals(what.getString())) {
        return;
      }

      final Form searching = new Form("Searching...");
      Display.getDisplay(Mapper.instance).setCurrent(searching);

      String searchTypeStr = searchType.getString(searchType.getSelectedIndex());
      if(searchTypeStr.equals("UNDEFINED")){
        searchTypeStr=null;
      }
      
      WgsPoint centerWgs=center;
      String distance = null;
      if(around.getString((around.getSelectedIndex())).equals("anywhere")){
        centerWgs=null;
      }else{
        distance  = "25000";
      }

      final CloudMadeGeocodingService service = new CloudMadeGeocodingService(this, "BC9A493B41014CAABB98F0471D759707",
          "666",centerWgs, null, what.getString(), searchTypeStr, 10, 0, null, false, distance);
      service.execute();
    }
  }

  public void searchResults(final KmlPlace[] kmlPlaces) {
    mapScreen.searchResults(kmlPlaces);
    
  }

  public void errors(final int errorCode) {
    System.out.println("Error > " + errorCode);
    final Form errorForm = new Form("Error:");
    if (errorCode == GeocodingService.NETWORK_ERROR) {
      errorForm.append("Network error");
    } else if (errorCode == GeocodingService.NOT_FOUND) {
      errorForm.append("Nothing found");
    } else if (errorCode == GeocodingService.SERVER_ERROR) {
      errorForm.append("Server error");
    }

    errorForm.addCommand(back);
    errorForm.setCommandListener(this);

    Display.getDisplay(Mapper.instance).setCurrent(errorForm);
  }
}
